﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class member_ConvertFileToSQL : System.Web.UI.Page
{
	public string EnterpriseName = "";
    public string UserID = "";
    public string UserPower = "";
    public string Footer = "";
	
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Init.islogin(ref UserID,ref EnterpriseName,ref UserPower))
        {
            Response.Redirect("/Login.aspx");
        }        
        if (!UserPower.Contains("Manager"))
        {
            Response.Write("你没有权限！");
            Response.End();
        }
        this.EnableViewState = false;
        Response.Write(Init.InitDefault());

        string GetStr = Request.Form["GetStr1"];
        string typeid = Request.Form["typeid"];
        string Page = Request.QueryString["Page"];
        if (string.IsNullOrEmpty(GetStr))
        {
            GetStr = Request.QueryString["GetStr"];
        }
        if (string.IsNullOrEmpty(typeid))
        {
            typeid = Request.QueryString["typeid"];
        }
        switch (Page)
        { 
            case"list":
                msg.Text = list(GetStr,typeid);
                break;
            case "listmx":
                Literal2.Text = index(GetStr,typeid);
                Literal1.Text += "<p><font face=\"Verdana, Arial, Helvetica, sans-serif\" color=\"#FF6600\">数据处理完毕,可以查询数据了0_0</font></p>\r\n";
                
                //msg.Text+=PageList2(FolderName);
                //msg.Text += PageList(FolderName);
                //string PathFolder = HttpContext.Current.Server.MapPath("~/" + FolderName);
                string PathFolder = "h:\\Share\\" + GetStr;
                msg.Text += GetAllFiles(PathFolder, typeid, GetStr);
                break;
            default:
                Literal2.Text = index(GetStr,typeid);
                break;
        }
    }

    Common Init = new Common();
    MsSqlHelper mssql = new MsSqlHelper();

    /// <summary>  
    /// 列出指定目录下及所其有子目录及子目录里更深层目录里的文件（需要递归）  
    /// </summary>  
    /// <param name="path"></param>  
    public string GetAllFiles(string path, string typeid, string FolderName = "")
    {
        try
        {
            string result = "";
            DirectoryInfo dir = new DirectoryInfo(path);

            //找到该目录下的文件  
            FileInfo[] fi = dir.GetFiles();
            int i = 0;
            foreach (FileInfo f in fi)
            {
                string p = f.FullName.ToString();
                p = p.Substring(p.LastIndexOf(path) + FolderName.Length).ToString();
                p = p.Replace("\\", "/");
                string fileinfoName = f.Name.Replace(f.Extension, "");
                fileinfoName = fileinfoName.PadRight(100, '_');
                string[] sArray = fileinfoName.Split(new char[2] { '_', '.' });
                result += "<tr class=\"searli\"><td>" + i + "</td><td>" + f.FullName.ToString() + "</td><td>" + p + "</td><td>" + f.Extension + "[" + typeid + "]</td>"
                       + "<td>[" + sArray[0] + "][" + sArray[1] + "][" + sArray[2] + "][" + sArray[3] + "][" + sArray[4] + "][" + sArray[5] + "]</td>";
                if (typeid == "fa")
                {
                    result += "<td>" + filetodata(sArray[0], typeid, f.Extension, p, sArray[0], sArray[2], sArray[3], sArray[4], sArray[5], f.Name) + "</td>";
                }
                else
                {
                    result += "<td>" + filetodata(sArray[1], typeid, f.Extension, p, sArray[0], sArray[2], sArray[3], sArray[4], sArray[5], f.Name) + "</td>";
                }
                result += "</tr>\r\n";
                i = i + 1;
            }

            //找到该目录下的所有目录再递归  
            DirectoryInfo[] subDir = dir.GetDirectories();
            foreach (DirectoryInfo d in subDir)
            {
                result += GetAllFiles(d.FullName,typeid, FolderName);
            }
            return result;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public string filetodata(string detailid,string typeid, string extension, string folderpath, string fzxx1, string fzxx2, string fzxx3, string fzxx4, string fzxx5, string url)
    {
        string msg = "";
        string sql = "";
        sql = "select biaoshi+right('00000000'+cast(recnum+1 as varchar(8)),8) from maxbh(nolock) where biaoshi='QCY'";
        string Imageid =mssql.GetString(sql);
        if (string.IsNullOrEmpty(Imageid))
        {
            sql = "insert into maxbh(biaoshi,recnum)values('QCY',0)";
            mssql.ExecuteSql(sql);
            Imageid = "QCY00000001";
        }
        /*
        sql = "insert into [ImageDoc]  "
          + "SELECT '" + Imageid + "' imageid,'IMT90000001' type_id,'检验报告' leibie,'SPH000" + detailid + "' detailid,'" + folderpath + "' folderpath,'" + extension + "' extend,'是' beactive,'" + fzxx1 + "' fzxx1,'" + fzxx2 + "' fzxx2,'" + fzxx3 + "' fzxx3,'' fzxx4,'' fzxx5,CONVERT(varchar(10),GETDATE(),120) jdrq,'" + url + "' url "
          + "FROM spkfk where spid='SPH000" + detailid + "' and '" + folderpath + "' not in(select folderpath from [ImageDoc](nolock))";
         */
        /*
        sql = "insert into [ImageDoc] (imageid,type_id,detailid,folderpath,extend,beactive,jdrq,url,lastmodifytime) "
          + "SELECT '" + Imageid + "' imageid,'" + typeid + "' type_id,spid,'" + folderpath + "' folderpath,'" + extension + "' extend,'是' beactive,CONVERT(varchar(10),GETDATE(),120) jdrq,'" + url + "' url,CONVERT(varchar(100),GETDATE(),120) lastmodifytime "
          + "FROM spkfk where spbh='" + detailid + "' "
          +"and '" + folderpath + "' not in(select isnull(folderpath,'') from [ImageDoc](nolock))";
         */
        if (typeid == "fa") 
        {
            sql = "insert into [ImageDoc] (imageid,type_id,detailid,folderpath,extend,beactive,jdrq,url,lastmodifytime) "
              + "SELECT top 1 '" + Imageid + "' imageid,'" + typeid + "' type_id,djbh,'" + folderpath + "' folderpath,'" + extension + "' extend,'是' beactive,CONVERT(varchar(10),GETDATE(),120) jdrq,'" + url + "' url,CONVERT(varchar(100),GETDATE(),120) lastmodifytime "
              + "FROM spls_rk where djbh='" + detailid + "' "
              + "and  not exists(select isnull(folderpath,'') from [ImageDoc](nolock) where folderpath='" + folderpath + "')";
        }
        else
        {
            sql = "insert into [ImageDoc] (imageid,type_id,detailid,folderpath,extend,beactive,jdrq,url,lastmodifytime) "
              + "SELECT '" + Imageid + "' imageid,'" + typeid + "' type_id,spid,'" + folderpath + "' folderpath,'" + extension + "' extend,'是' beactive,CONVERT(varchar(10),GETDATE(),120) jdrq,'" + url + "' url,CONVERT(varchar(100),GETDATE(),120) lastmodifytime "
              + "FROM spkfk where spbh='" + detailid + "' "
              + "and  not exists(select isnull(folderpath,'') from [ImageDoc](nolock) where folderpath='" + folderpath + "')";
        }
        if (Init.IsDebug)
        {
            ResultDeBug.Text = sql+typeid;
        }
        msg += "<li>";
        if (mssql.ExecuteSql(sql) >= 1)
        {
            sql = "update maxbh set recnum=recnum+1 where biaoshi='QCY'";
            mssql.ExecuteSql(sql);
            msg += ("<font color=FF6600>上传成功</font>");
        }
        else
        {
            msg += ("<font color=FF0000>数据已上传或无信息请勿重复上传</font>");
        }

        msg += "</li>\r\n";
        return msg;
    }

    public string list(string GetStr,string typeid)
    {
        return ("" +
         "<script language=\"JavaScript\">\r\n" +
          "<!--\r\n" +
         "var url = 'ConvertFileToSQL.aspx?Page=listmx&GetStr=" + GetStr + "&typeid="+typeid+"';\r\n" +
          "//-->\r\n" +
          "</script>\r\n" +
          "<body scroll=\"no\" bgcolor=\"#FFFFFF\" onLoad=\"location.href = url\">\r\n" +
          "<div align=\"center\" style=\"text-align:center;line-height:100px\">\r\n" +
          "<p>\r\n" +
          "<img src=\"/Public/Home/images/loadingBig.gif\">\r\n" +
          "</p>\r\n" +
          "<p><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"12\" color=\"#FF6600\">正在生成数据请等待....</font>\r\n" +
          "</p>\r\n" +
          "<p>\r\n" +
          "<script>\r\n" +
          "<!--\r\n" +
         "if (document.layers)\r\n" +
          "     document.write('<Layer src=\"' + url + '\" VISIBILITY=\"hide\"> </Layer>');\r\n" +
           "    else if (document.all || document.getElementById)\r\n" +
            "    document.write('<iframe src=\"' + url + '\" style=\"visibility: hidden;\"></iframe>');\r\n" +
          "else location.href = url;\r\n" +
          "//-->\r\n" +
          "</script>\r\n" +
          "</p>\r\n" +
          "</div>\r\n" +
          "</body>\r\n"
            );
    }
   

    public string index(string GetStr,string typeid)
    {
        string result="";
        result += "<form name=\"form\" id=\"form\" method=\"post\" action=\"ConvertFileToSQL.aspx?Page=list\">\r\n" +
                 "<span class=\"s1\">\r\n"+
                 "<b>文件夹名</b><input type=\"text\" name=\"GetStr1\" value=\"" + GetStr + "\" placeholder=\"一般格式为:20160101\" style=\"width:140px;\"> \r\n" +
                 "<b>选择类型</b><select name=\"typeid\" style=\"select\"> \r\n";
       result += (typeid == "sf") ? "<option value =\"sf\" selected = \"selected\">标准</option> \r\n" : "<option value =\"sf\">标准</option> \r\n";
       result += (typeid == "pj") ? "<option value =\"pj\" selected = \"selected\">批件</option> \r\n" : "<option value =\"pj\">批件</option> \r\n";
       result += (typeid == "sm") ? "<option value =\"sm\" selected = \"selected\">说明书</option> \r\n" : "<option value =\"sm\">说明书</option> \r\n";
       result += (typeid == "fa") ? "<option value =\"fa\" selected = \"selected\">发票</option> \r\n" : "<option value =\"fa\">发票</option> \r\n";
       result += (typeid == "bz") ? "<option value =\"bz\" selected = \"selected\">包装</option> \r\n" : "<option value =\"bz\">包装</option> \r\n";
       result += "</select> \r\n" +
                 "</span>\r\n" +
                 "<input type=\"submit\" name=\"Submit\" class=\"msbut\" value=\"提  交\" />\r\n" +
                 "</form>\r\n";
        return result;
    }


}
